package com.ido.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Create by zoub
 * Date 2025/5/8 10:08 AM
 */
@Slf4j
@Component
public class RedisLock {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 尝试获取锁(默认5分钟过期)
     *
     * @param key
     * @param value
     * @return
     */
    public boolean tryLock(String key, String value) {
        return tryLock(key, value, 300);
    }

    public boolean tryLock(String key, String value, long timeout) {
        try {
            return redisTemplate.opsForValue().setIfAbsent(key, value, timeout, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("{}:获取锁失败，e={}", key, e.getMessage());
        }
        return false;
    }


    /**
     * 解锁
     */
    public void unlock(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("{}:unlock失败，e={}", key, e.getMessage());
        }

    }
}

